package clientproject;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import serverproject.model.MemberList;

import clientproject.window.ClientWindow;

public class ReceiverThread extends Thread
{
	private Socket			socket;
	private ClientWindow	clientWindow;

	public ReceiverThread(Socket socket , ClientWindow clientWindow)
	{
		this.socket = socket;
		this.clientWindow = clientWindow;
	}

	public void run()
	{
		try
		{

			while (true)
			{
				ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
				String str = null;
				MemberList memberList = null;
				try
				{
					Object object = ois.readObject();

					if (object instanceof String)
						str = (String) object;
					else
						memberList = (MemberList) object;
				} catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (str == null)
				{
					System.out.println("후후훗");
					JTable table = clientWindow.getMemberTable();

					for (String st : memberList.getMemberList())
					{
						String[] string = { st }; // addRow를 하기위하여 임시생성
						DefaultTableModel model = (DefaultTableModel) table.getModel();
						model.addRow(string);
					}

					table.scrollRectToVisible(table.getCellRect(table.getRowCount() - 1, table.getColumnCount(), true)); // JScrollPane에서 JTable의 가장
																															// 마지막
																															// 줄로 가도록
				}
				else
				{
					JTable table = clientWindow.getTable();

					String[] string = { str }; // addRow를 하기위하여 임시생성
					DefaultTableModel model = (DefaultTableModel) table.getModel();
					model.addRow(string);

					table.scrollRectToVisible(table.getCellRect(table.getRowCount() - 1, table.getColumnCount(), true)); // JScrollPane에서 JTable의 가장
																															// 마지막
																															// 줄로 가도록
				}
			}
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
